﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel.Composition;
using TweetStream.Extensions.Contracts;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.Net.Browser;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Xml;
using System.Json;
using System.Windows.Browser;

namespace TweetStream.Extensions.Trim
{
    [Export ( typeof(IThirdPartyContent))]
	public partial class InlineImage : UserControl, IThirdPartyContent
	{

        //public delegate void ShowImageUriHandler(object sender, IHLArgs args);
        //public delegate void ShowHtmlUriHandler(object sender, IHTMLArgs args);

        //public event ShowImageUriHandler ShowImageUri;
        //public event ShowHtmlUriHandler ShowHtmlUri;

		public InlineImage()
		{
			// Required to initialize variables
			InitializeComponent();
		}


        #region Source


        public ImageSource Source
        {
            get { return (ImageSource)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(ImageSource), typeof(InlineImage), new PropertyMetadata(SourceChanged));

        private static void SourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            ((InlineImage)obj).imgSource.Source = (ImageSource)args.NewValue;
        }
        #endregion


        void IThirdPartyContent.InitControl(InitMessage msg)
        {


            Uri longUrlPleaseUri = GetLongUrlPleaseUri(new List<String>() { msg.Url });

            State st = new State()
            {
                DynamicControlsContainer = msg.DynamicControlsContainer,
                Url = msg.Url,
                Key = msg.Key,
                Uri = new Uri(msg.Url, UriKind.Absolute),
                LoadingAnimation = msg.LoadingAnimation,
                LoadingAnimationContainer = msg.LoadingAnimationContainer

            };


            bool httpResult = HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            bool httpsResult = HttpWebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);

            HttpWebRequest rq = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(longUrlPleaseUri);
            rq.Method = "GET";

            rq.BeginGetResponse(
            new AsyncCallback(
               r =>
               {
                   State st1 = (State)r.AsyncState;

                   try
                   {
                       WebResponse rs = rq.EndGetResponse(r);
                       using (Stream stream = rs.GetResponseStream())
                       {
                           using (StreamReader sr = new StreamReader(stream))
                           {
                               string responseText = sr.ReadToEnd();


                               JsonObject jsonobject = (JsonObject)JsonValue.Parse(responseText);
                               JsonValue val = null;

                               foreach (var i in jsonobject.Keys)
                               {
                                   
                                   jsonobject.TryGetValue(i, out val);
                               }


                               if (val != null)
                               {
                                   Deployment.Current.Dispatcher.BeginInvoke(delegate {


                                       UserControl ctl = DoCheck(st1.Key, val.ToString());
                                       ctl.UpdateLayout();
                                       st1.DynamicControlsContainer.Children.Clear();
                                       st1.DynamicControlsContainer.Children.Add(ctl);
                                       st1.DynamicControlsContainer.Visibility = Visibility.Visible;
                                       st1.DynamicControlsContainer.Height += (ctl).ActualHeight;
                                   });

                               }

                           }
                       }


                   }
                   catch (WebException ex)
                   {

                   }
                   finally
                   {
                       Deployment.Current.Dispatcher.BeginInvoke(delegate
                       {
                           st1.LoadingAnimation.Stop();
                           st1.LoadingAnimationContainer.Children.Clear();
                       });
                       
                   }
               }), st);


        }




        private static Uri GetLongUrlPleaseUri(IEnumerable<String> shortUrls)
        {
            // Single or multiple short URLs may be requested.             
            // http://www.longurlplease.com/api/v1.1?q=http://bit.ly/enAo&q=http://short.ie/bestxkcd

            var parameters = new StringBuilder();

            String delimiter = string.Empty;
            foreach (var url in shortUrls)
            {
                parameters.Append(delimiter).AppendFormat("q={0}", url);
                delimiter = "&";
            }

            return new Uri(string.Format("http://www.longurlplease.com/api/v1.1?{0}", parameters), UriKind.Absolute);
        }



        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            State st = (State)e.UserState;

            try
            {
                string res = e.Result;

          

                UserControl ctl = DoCheck(st.Key, res);

                if (ctl != null)
                {
                    string sType = ctl.GetType().Name;

                    if (sType.ToLower().Contains("image"))
                    {
                        //if (ShowImageUri != null) ShowImageUri(ctl, new IHLArgs(st.DynamicControlsContainer));
                        ctl.UpdateLayout();
                        st.DynamicControlsContainer.Children.Clear();
                        st.DynamicControlsContainer.Children.Add(ctl);
                        st.DynamicControlsContainer.Visibility = Visibility.Visible;
                        st.DynamicControlsContainer.Height += (ctl).ActualHeight;
                        
                    }
                    else if (sType.ToLower().Contains("html"))
                    {
                        //if (ShowHtmlUri != null) ShowHtmlUri(ctl, new IHTMLArgs(st.DynamicControlsContainer));
                        ctl.UpdateLayout();
                        st.DynamicControlsContainer.Children.Clear();
                        st.DynamicControlsContainer.Children.Add(ctl);
                        st.DynamicControlsContainer.Visibility = Visibility.Visible;
                        st.DynamicControlsContainer.Height += (ctl).ActualHeight;
                        
                    }


                }


            }
            catch { }
            finally
            {
                st.LoadingAnimation.Stop();
                st.LoadingAnimationContainer.Children.Clear();
            }

        }


        UserControl IThirdPartyContent.DoCheck(string key, string contentToParse)
        {

            return DoCheck(key, contentToParse);
        }

        UserControl DoCheck(string key, string contentToParse)
        {

            if (key == "trim")
            {
                
                InlineImage ctl = new InlineImage()
                {
                    HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                    VerticalAlignment = System.Windows.VerticalAlignment.Top,
                    Width = 220
                };

                ctl.txtLongUrl.Text = HttpUtility.UrlDecode(contentToParse.Replace("\\/","\\"));
                return ctl;

            }

            return null;
        }

        bool IThirdPartyContent.CheckIfAutoLoad(string key)
        {
            if (key == "trim") return true;

            return false;
        }


        public string RetrieveKey(string url)
        {
            if (url.ToLower().Contains("tr.im")) return "trim";
            else return string.Empty;
        }


    }

    public class State
    {
        public Grid DynamicControlsContainer { get; set; }
        public string Key { get; set; }
        public string Url { get; set; }
        public Uri Uri { get; set; }
        public Storyboard LoadingAnimation { get; set; }
        public Grid LoadingAnimationContainer { get; set; }
    }

    [DataContract]
    public class rowData
    {
        [DataMember]
        public string ShortUrl;
        [DataMember]
        public string ExpandedUrl;
    }   

}